<template>
  <div>
    <el-breadcrumb class="breadcrumb page-title" separator="/">
      <el-breadcrumb-item :to="{ path: '/company' }">{{$t('m.MyProfile')}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form ref="formName" :model="form" :rules="rulesName" label-width="280px" class="form-box container-padding">

      <el-form-item label="Username" prop="name">
        <el-input v-model="form.name" :show-message="true" :class="correct? '': 'error-submit'"></el-input>
      </el-form-item>
      <div style="margin-left: 280px;margin-top:-5px;" class="el-form-item">
        {{$t('m.Letternumberunderscoreperiodsonly')}}<br/>
        {{$t('m.Nomorethanoneunderscore')}}<br/>
        {{$t('m.Letternumbercharacters')}}
      </div>

      <el-form-item :label="$t('m.Photo')" class="cover-photo-box">
        <!--<el-upload-->
          <!--class="upload-demo"-->
          <!--v-bind:class="{ activeShowButton: isHideButton }"-->
          <!--ref="upload"-->
          <!--:limit="1"-->
          <!--list-type="picture-card"-->
          <!--:action="updateCompanyLogoUrl"-->
          <!--:on-preview="handlePreview"-->
          <!--:on-remove="handleRemove"-->
          <!--:on-change="handleChange"-->
          <!--:file-list="fileList"-->
          <!--:on-error="imgUploadError"-->
          <!--:on-success="imgUploadSuccess"-->
          <!--:auto-upload="false">-->
          <!--<i class="el-icon-plus"></i>-->
        <!--</el-upload>-->
        <uploadimages ref="uploadPhotos" :coverPhoto.sync="coverPhoto"></uploadimages>
        <el-dialog :visible.sync="dialogVisible" size="tiny" :modal="false">
          <img width="100%" :src="coverPhoto" alt="">
        </el-dialog>
        <el-button class="upload-image" @click="uploadUserPhoto()">Upload photo</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="warning" @click="onSubmitTop">{{$t('m.Save')}}</el-button>
      </el-form-item>
    </el-form>
    <el-form ref="form" :model="form" :rules="rules" label-width="280px" class="form-box container-padding" style="padding-top: 0;">

      <div class="company-title">
        <h3>{{$t('m.Foradvertisementcontactpleaseenter')}}</h3>
        <div class="lines"></div>
        <!--<div class="line-company">For advertisement contact, please enter</div>-->
      </div>

      <el-form-item :label="$t('m.Phoneseparatemycomma')" prop="companyPhone">
        <el-input type="textarea" v-model="form.companyPhone" :rows="2"></el-input>
      </el-form-item>

      <el-form-item :label="$t('m.Email')">
        <el-input v-model="form.email"></el-input>
      </el-form-item>

      <!--<el-form-item label="Company Name" prop="companyName">-->
        <!--<el-input v-model="form.companyName"></el-input>-->
      <!--</el-form-item>-->

      <el-form-item :label="$t('m.Region')" prop="region">
        <el-cascader :options="regionOptions" @change="regionChange" v-model="form.region" ref="ruleForm"
                     :value="form.region"
                     placeholder=""></el-cascader>
      </el-form-item>

      <el-form-item :label="$t('m.Township')" prop="township">
        <el-select v-model="form.township" :label="form.township" :value="form.township" placeholder="">
          <el-option v-for="(item, index) in townshipJson" :label="item.text" :key="index" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="warning" @click="onSubmit">{{$t('m.Save')}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import township from '@/json/township'
  import { developerManage, updateCompanyLogoUrl, updateCompanyMessage, updateProfile, companyPhotos} from '../../api/apiNext'
  import qs from 'qs'
  import uploadimages from '@/components/maincomponents/uploadimages'

  export default {
    name: 'company',
    prpps: [
      'onUserNameChange'
    ],
    data () {
      return {
        updateCompanyLogoUrl: updateCompanyLogoUrl,
        limit: 1,
        form: {
          region: [],
          township: '',
          companyName: '',
          companyPhone: '',
          email: '',
          name: ''
        },
        regionOptions: [{value: '2', label: 'Yangon'},
          {value: '3', label: 'Mandalay'},
          {value: '4', label: 'Bago'},
          {value: '5', label: 'Ayeyarwady'},
          {value: '6', label: 'Chin'},
          {value: '7', label: 'Kachin'},
          {value: '8', label: 'Kayah'},
          {value: '9', label: 'Kayin'},
          {value: '10', label: 'Magway'},
          {value: '11', label: 'Mon'},
          {value: '12', label: 'Rakhine'},
          {value: '13', label: 'Sagaing'},
          {value: '14', label: 'Shan'},
          {value: '15', label: 'Tanintharyi'},
          {value: '16', label: 'Nay Pyi Taw'}],
        townshipJson: [],
        fileList: [{}],
        dialogImageUrl: '',
        dialogVisible: false,
        rules: {
          region: [
            {required: true, type: 'array', message: 'please enter region', trigger: 'blur'}
          ],
          township: [
            {required: true, type: 'number', message: 'please enter township', trigger: 'change'}
          ],
          companyPhone: [
            {required: true, message: 'please enter phone', trigger: 'blur'}
          ],
        },
        rulesName: {
          name: [
            {required: true, message: 'please enter username', trigger: 'blur'}
          ],
        },
        townshipInit: township,
        isHideButton: true,
        correct: true,
        coverPhoto: '',
      }
    },
    components: {
      uploadimages
    },
    methods: {
      imgUploadError (err, file, fileList) {
        if (err.errorID == '100004') {
          this.showToast(err.errorID)
          this.$router.push('/login')
        }
      },
      imgUploadSuccess (response, file, fileList) {
        if (response.errorID == '100004') {
          this.showToast(response.errorID)
          this.$router.push('/login')
        }
      },
      onSubmitTop () {
        // 提交图片11
        // this.$refs.upload.submit((res) => {
        //   console.log(res)
        //   this.fileList[0].name = ''
        //   this.fileList[0].url = res.url
        //   this.$message.success('Image Upadte Success')
        // })
        this.$refs['formName'].validate((valid) => {
          if (valid) {
            // 修改名称的接口
            let sendDataName = {
              'name': this.translateZTUnicode(this.form.name),
            }
            sendDataName = qs.stringify(sendDataName)
            updateProfile(sendDataName).then((res) => {
              if (res.data.errorID === 100004) {
                this.showToast(res.data.errorID)
                this.$router.push('/login')
                return
              }
              if (res.data.errorID === 0) {
                localStorage.setItem('username', this.form.name)
                this.$store.commit('updateUserName', this.form.name)
                this.uploadUserPhoto(res)
                this.correct = true
              } else if (res.data.errorID === 100007){
                this.correct = false
                this.showToast(res.data.errorID, 'Error, please check your username.')
              } else {
                this.correct = true
                this.showToast(res.data.errorID)
              }
            }).catch((error) => {
              this.showToast(error.errorID)
            })

          }else {
            return false
          }
        })
      },
      uploadUserPhoto(response){
        let res = response || ''
        let uploadCoverPhoto = this.$refs.uploadPhotos.blobsObj
        if (uploadCoverPhoto.length > 0) {
          let formData = new FormData()
          formData.append('file', uploadCoverPhoto[0])
          let config = {
            'Content-Type': 'multipart/form-data'
          }
          companyPhotos(formData, config).then((res) => {
            if (res.data) {
              if (res.data.errorID === 0) {
                // this.````3.success('successful')
                // let resData = res.data.object
                // this.coverPhoto = resData
                this.showToast(res.data.errorID)
                this.$refs.uploadPhotos.removeAllImage()

                // 调用接口刷新服务器的数据
                this.getCompanyMessage()

              }else if (res.data.errorID === 100004) {
                this.$router.push('/login')
                this.showToast(res.data.errorID)
              } else {
                this.showToast(res.data.errorID)
              }
            }
          }).catch((error) => {
            this.showToast(error.errorID)
          })
        } else {
          // 应该发送空/原先的url
          if (res) {
            this.showToast(res.data.errorID)
          }
          // 调用接口刷新服务器的数据
          this.getCompanyMessage()
          let resData = this.$refs.uploadPhotos.coverPhoto
          this.coverPhoto = resData
        }
      },
      onSubmit () {
        // 提交其他
        this.$refs.form.validate((valid) => {
          if (valid) {
            // 公司信息处理
            let sendData = {
              // 'companyName': this.form.companyName,
              'email': this.form.email,
              'phone': this.form.companyPhone,
              'regionId': this.form.region[0],
              'townshipId': this.form.township
            }
            sendData = qs.stringify(sendData)
            updateCompanyMessage(sendData).then((res) => {
              if (res.data.errorID === 100004) {
                this.showToast(res.data.errorID)
                this.$router.push('/login')
                return
              }
              // 公司信息保存成功 errorID = 0
              if (res.data.errorID === 0) {
                this.showToast(res.data.errorID)
              }

              // 调用接口刷新服务器的数据
              this.getCompanyMessage()

            }).catch((error) => {
              console.log(error)
            })

          } else {
            return false
          }
        })
      },
      // 图片上传的逻辑
      submitUpload () {
        // 提交图片的操作
        // this.$refs.upload.submit()
      },// helper.js
      handleRemove (file, fileList) {
        this.fileList = []
        this.isHideButton = false
      },
      handleChange (file, fileList) {
        this.isHideButton = true

        // 图片压缩
        // let img = new Image()
        // img.src = file.url
        // console.log(img.src, '原始图片')
        // let canvas = document.createElement('canvas')
        // let context = canvas.getContext('2d')
        // // 图片原始尺寸
        // let originWidth = img.width
        // var originHeight = img.height
        // // 最大尺寸限制
        // let maxWidth = 600
        // let maxHeight = 600
        // // 目标尺寸
        // let targetWidth = originWidth
        // let targetHeight = originHeight
        // // 图片尺寸超过400x400的限制
        // if (originWidth > maxWidth || originHeight > maxHeight) {
        //   if (originWidth / originHeight > maxWidth / maxHeight) {
        //     // 更宽，按照宽度限定尺寸
        //     targetWidth = maxWidth
        //     targetHeight = Math.round(maxWidth * (originHeight / originWidth))
        //   } else {
        //     targetHeight = maxHeight
        //     targetWidth = Math.round(maxHeight * (originWidth / originHeight))
        //   }
        // }
        // // canvas对图片进行缩放
        // canvas.width = targetWidth
        // canvas.height = targetHeight
        // // 清除画布
        // context.clearRect(0, 0, targetWidth, targetHeight)
        // // 图片压缩
        // context.drawImage(img, 0, 0, targetWidth, targetHeight)
        // console.log(canvas, context, 'canvas')
        // // canvas转为blob并上传
        // canvas.toBlob((blob) => {
        //   console.log(file, blob, '修改之前的数据')
        //   file.url = URL.createObjectURL(blob)
        //   console.log(file, blob, '修改了的数据')
        //
        //   fileList.push(file)
        //
        // }, 'image/png', 0.6)

      },
      handlePreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 发起请求公司信息
      getCompanyMessage () {
        let developerId = localStorage.getItem('developerId')
        developerManage(developerId).then((res) => {
          if (res.data.errorID === 100004) {
            this.showToast(res.data.errorID)
            this.$router.push('/login')
            return
          }

          let data = res.data.object
          this.form.region = []
          this.form.region[0] = data.regionId ? String(data.regionId) : ''
          this.form.township = data.townshipId ? Number(data.townshipId) : ''

          // 动态设置township数组---联动
          let townShipArr = []
          for (var i = 0; i < this.townshipInit.length; i++) {
            if (this.form.region[0] == this.townshipInit[i].regionId) {
              townShipArr.push(this.townshipInit[i])
            }
          }
          this.townshipJson = []
          this.townshipJson = townShipArr

          this.form.companyName = data.companyName
          this.form.companyPhone = data.phone
          this.form.email = data.email

          this.coverPhoto = data.companyLogo
//          this.fileList[0].url = 'http://game.dlintech.com/images/ca/eefe65514e73d9503ddc99b874ca75.jpg'
          this.fileList[0].name = ''
          if (data.companyLogo) {
            this.isHideButton = true
          }
        })
          .catch((error) => {
            console.log(error)
          })
      },
      // regionChange
      regionChange (value) {
        // 联动
        let townShipArr = []
        for (var i = 0; i < this.townshipInit.length; i++) {
          if (value[0] == this.townshipInit[i].regionId) {
            townShipArr.push(this.townshipInit[i])
          }
        }
        this.form.township = ''
        this.townshipJson = []
        this.townshipJson = townShipArr
      },
      translateUTZaw(str){
        if (!str) return '';
        return this.$translateLang(str, 'unicodeTozawgyi')
      },
      translateZTUnicode(str){
        if (!str) return '';
        return this.$translateLang(str, 'zawgyiTounicode')
      },
    },
    mounted () {
      this.getCompanyMessage()
      this.form.name = localStorage.getItem('username') || ''
    }
  }
</script>

<style>
  .form-box {
    width: 600px;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px !important;
  }

  .container-padding {
    padding: 40px 40px 0 40px;
  }

  .line-company {
    height: 30px;
    border-top: 1px solid #e6e6e6;
    padding: 15px 0 10px 20px;
  }

  .activeShowButton .el-upload {
    display: none !important;
  }

  .company-title {
    margin-top: 20px;
  }

  .company-title .lines {
    padding: 10px 0 20px 0;
    border-top: 1px solid #d4d3d3;
  }

  .cover-photo-box .photo-title {
    display: none;
  }

  .cover-photo-box .photos-box ul li{
    width: 100px;
    height: 100px;
    margin-top: -15px;
  }

  .cover-photo-box  .glyphicon {
    line-height: 100px;
  }
  .cover-photo-box .upload-image{
    position: absolute;
    top: 10px;
    right: 30px;
  }
  .el-form-item .error-submit .el-input__inner{
    border-color: #fa5555 !important;
  }
</style>
